import { ElMessage, ElMessageBox } from 'element-plus';
import { jsPlumb } from 'jsplumb';

import { LocationQuery } from 'vue-router';
import { jsplumbDefaults, jsplumbMakeSource, jsplumbMakeTarget, jsplumbConnect } from '../config';
import Contextmenu from '../cpns/contextmenu/index.vue';
import Drawer from '../cpns/drawer/index.vue';
import EventHandler from '../cpns/eventHandler/index.vue';
import { httpReqeustApi } from '/@/api/linxyun/base';
// import FuncPieceCall from './cpns/funcPieceCall/index.vue';
import { toHex, toHex1 } from '/@/utils/extendMethods';
interface IState {
	currentFlowAreaID: number | null;
	dropdownLine: IDropdownLine;
	dropdownNode: IDropdownLine;
	jsplumbData: Record<string, any>[];
	currentPushLineListIndex: number | null;
	eventhandlerDialog: boolean;
	isAddEventhandler: boolean;
	flowEventList: any[];
	currentIndex: null | string;
	EditCallFB: boolean;
	dragFBToEventIndex: null | number;
	funcPieceCalldialog: boolean;
	EventType: 'Timeout' | 'Init' | null;
	isCodeEditorDialog: boolean;
	CSCode: string;
	addCodeOrEditCode: 'add' | 'edit';
	timer: NodeJS.Timeout;
	FBDateilData: Record<string, any>;
	isFBDateildialog: boolean;
	activeInputVal: string;
	addEventVarDialog: boolean;
	currentEventVarIndex: null | number;
	isEditEventVar: boolean;
}
interface IDropdownLine {
	x: number | null;
	y: number | null;
}
interface IKeyword {
	// 所有关键字
	e: string[]; // 事件变量
	g: string[]; // 全局变量
	s: string[]; // 会话变量
	c: string[]; // 常量
	fbnameList: string[]; // 流程块名称
}

/**
 * 流程事件相关的函数及变量
 * @param jsPlumbInstList
 * @param routeParams
 * @param keyword
 * @returns
 */
export default function (jsPlumbInstList: any[], routeParams: LocationQuery, keyword: IKeyword) {
	const httpRequest = httpReqeustApi();
	const state = reactive<IState>({
		currentFlowAreaID: null,
		dropdownLine: { x: null, y: null },
		dropdownNode: { x: null, y: null },
		jsplumbData: [],
		currentPushLineListIndex: null,
		eventhandlerDialog: false,
		isAddEventhandler: true,
		flowEventList: [],
		currentIndex: null,
		EditCallFB: false,
		dragFBToEventIndex: null,
		funcPieceCalldialog: false,
		EventType: null,
		isCodeEditorDialog: false,
		CSCode: '',
		addCodeOrEditCode: 'add',
		timer: null,
		FBDateilData: {},
		isFBDateildialog: false,
		activeInputVal: '',
		addEventVarDialog: false,
		currentEventVarIndex: null,
		isEditEventVar: false,
	});
	const jsPlumbConfig = {
		jsplumbMakeSource,
		jsplumbMakeTarget,
		jsplumbConnect,
	};
	const contextmenuLineRef = ref<InstanceType<typeof Contextmenu>>();
	const contextmenuNodeRef = ref<InstanceType<typeof Contextmenu>>();
	const drawerRef = ref<InstanceType<typeof Drawer>>();
	const eventHandlerRef = ref<InstanceType<typeof EventHandler>>();
	const FBCallRef = ref<InstanceType<typeof EventHandler>>();
	const createJsPlumbInst = (i: number) => {
		const jsPlumbInst: any = jsPlumb.getInstance();
		jsPlumbInst.ready(() => {
			const containerName = 'workflow-' + (i + 1);
			console.log(containerName);
			jsPlumbInst.setContainer(containerName);
			jsPlumbInst.fire('jsPlumbDemoLoaded', jsPlumbInst);
			// 导入默认配置
			jsPlumbInst.importDefaults(jsplumbDefaults);
			// 会使整个jsPlumb立即重绘。
			jsPlumbInst.setSuspendDrawing(false, true);
			// 点击线弹出右键菜单
			jsPlumbInst.bind('contextmenu', (conn: any, originalEvent: MouseEvent) => {
				originalEvent.preventDefault();
				state.currentFlowAreaID = i;
				console.log('contextmenu', conn, i);
				const { sourceId, targetId } = conn;

				const { clientX, clientY } = originalEvent;
				state.dropdownLine.x = clientX;
				state.dropdownLine.y = clientY;
				console.log('targetID:', targetId);
				const v = state.jsplumbData[i].nodeList.find((v) => v.fbname === targetId);
				const line = state.jsplumbData[i].lineList.find((v) => v.sourceId === sourceId && v.targetId === targetId);
				if (line.sourceId.indexOf('start-fb-') !== -1) {
					return ElMessage({
						type: 'warning',
						message: '关联开始的线条不可以编辑',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				}
				v.type = 'line';
				v.label = line.label;
				v.antenna = line.antenna;
				v.showClose = true;
				console.log('v', v);
				console.log('line', line);
				contextmenuLineRef.value.openContextmenu(v, conn);
			});
			// 连线之前
			jsPlumbInst.bind('beforeDrop', (conn) => {
				const { sourceId, targetId } = conn;

				const index = state.jsplumbData[i].lineList.findIndex((v) => {
					return v.sourceId === sourceId && v.targetId === targetId;
				});

				if (index !== -1 || /start-fb/.test(sourceId) || /start-fb/.test(targetId)) {
					ElMessage({
						type: 'warning',
						message: '不可以重复关联',
						duration: BASE_API.MSG_SHOW_TIME,
					});
					return;
				}
				let num = 0;

				for (let ii = 0; i < state.jsplumbData[i].lineList.length; ii++) {
					if (state.jsplumbData[i].lineList[ii].sourceId === sourceId) {
						if (num >= 3) {
							num += 1;
							break;
						}
						num += 1;
					}
				}
				if (num >= 3) {
					ElMessage({
						type: 'warning',
						message: '连接数量已超过上限，不可以在进行连接了',
						duration: BASE_API.MSG_SHOW_TIME,
					});
					return false;
				} else {
					return true;
				}
			});

			// 连线时
			jsPlumbInst.bind('connection', (conn) => {
				state.currentFlowAreaID = i;

				const { sourceId, targetId } = conn;
				console.log('connection', sourceId, targetId);

				if (/start-fb/.test(sourceId) || /start-fb/.test(targetId)) return;

				const data = {
					sourceId,
					targetId,
					label: '',
					isPop: true,
				};
				const nodeList = state.jsplumbData[i].nodeList;
				const targetIndex = nodeList.findIndex((item) => item.fbname === targetId);
				const sourceIndex = nodeList.findIndex((item) => item.fbname === sourceId);
				// fbitem['contextMenuClickId'] = 1
				console.log('getAllConnections', sourceIndex);
				const connections = jsPlumbInstList[i].getAllConnections();
				console.log('conn:', nodeList[targetIndex]);
				const triggerCondArr = nodeList[targetIndex].TriggerCond.split(',');
				for (let i = 0; i < triggerCondArr.length; i++) {
					if (triggerCondArr[i]) {
						const arr = triggerCondArr[i].split('.');
						const fbid = arr[0].substring(2, arr[0].length - 1);
						const nodeItem = nodeList.find((n) => {
							return fbid === n.CallFBID;
						});
						if (arr[1].indexOf('0') === 2) {
							getConnection(nodeItem.fbname, targetId).setPaintStyle({ stroke: '#409EFF' });
						} else if (arr[1].indexOf('1') === 2) {
							getConnection(nodeItem.fbname, targetId).setPaintStyle({ stroke: '#67C23A' });
						} else if (arr[1].indexOf('2') === 2) {
							getConnection(nodeItem.fbname, targetId).setPaintStyle({ stroke: '#F56C6C' });
						}
					}
				}
				function getConnection(sourceId, targetId) {
					const connect = connections.find((c) => {
						return c.targetId === targetId && c.sourceId === sourceId;
					});
					console.log('connect66666:', connect);
					return connect;
				}
				console.log('data:', data);

				const lineItem = state.jsplumbData[i].lineList.find((item) => item.sourceId === sourceId && item.targetId === targetId);
				// console.log('lineItem:', lineItem)
				if (lineItem) {
					return;
				}
				const lineListLength = state.jsplumbData[i].lineList.push(data);
				state.currentPushLineListIndex = lineListLength - 1;
				if (data.isPop) {
					onCurrentLineClick(
						{
							...nodeList[targetIndex],
							contextMenuClickId: 1,
							type: 'line',
							label: '',
							showClose: false,
						},
						conn.connection
					);
				}
			});

			// 删除连线时回调函数
			jsPlumbInst.bind('connectionDetached', (conn) => {
				const { sourceId, targetId } = conn;
				state.jsplumbData[i].lineList = state.jsplumbData[i].lineList.filter((line) => {
					if (line.sourceId === sourceId && line.targetId === targetId) {
						return false;
					}
					return true;
				});
			});
		});
		return jsPlumbInst;
	};
	// 初始化节点、线的链接
	const initJsPlumbConnection = (index: number) => {
		console.log('jsPlumbInstList:', jsPlumbInstList);
		if (!state.jsplumbData[index]) return;
		// 节点
		state.jsplumbData[index].nodeList.forEach((v) => {
			// console.log('initJsPlumbConnection', index, this.jsPlumbInst[index], v)
			// 整个节点作为source或者target
			jsPlumbInstList[index].makeSource(v.fbname, jsPlumbConfig.jsplumbMakeSource);
			// 整个节点作为source或者target
			jsPlumbInstList[index].makeTarget(v.fbname, jsPlumbConfig.jsplumbMakeTarget, jsPlumbConfig.jsplumbConnect);
			// 设置节点可以拖拽（此处为id值，非class）
			jsPlumbInstList[index].draggable(v.fbname, {
				containment: 'parent',
				stop: (el) => {
					state.jsplumbData[index].nodeList.forEach((v) => {
						if (v.fbname === el.el.id) {
							// 节点x, y重新赋值，防止再次从左侧导航中拖拽节点时，x, y恢复默认
							v.left = `${el.pos[0]}px`;
							v.top = `${el.pos[1]}px`;
						}
					});
				},
			});
		});
		// 线
		state.jsplumbData[index].lineList.forEach((v) => {
			console.log('vvvvvvvvvvv', v);
			console.log('jsPlumbInstList', jsPlumbInstList[index]);
			jsPlumbInstList[index].connect(
				{
					source: v.sourceId,
					target: v.targetId,
					label: v.label,
				},
				jsPlumbConfig.jsplumbConnect
			);
		});
	};

	// 右键节点触发
	const handleNodeContextMenu = (nodeItem, event) => {
		console.log(event);
		if (/start-fb|end-fb|session-end-fb/.test(nodeItem.fbname)) {
			return ElMessage({
				type: 'warning',
				message: '该功能块没有触发事件',
				duration: BASE_API.MSG_SHOW_TIME,
			});
		}
		const { clientX, clientY } = event;
		state.dropdownNode.x = clientX;
		state.dropdownNode.y = clientY;
		contextmenuNodeRef.value.openContextmenu(nodeItem);
	};
	// 右侧内容区-当前项右键菜单点击回调(线)
	const onCurrentLineClick = (item, conn) => {
		console.log('drawerRef', drawerRef.value);
		console.log('onCurrentLineClick', item, conn);
		const { contextMenuClickId } = item;
		const { endpoints, sourceId, targetId } = conn;
		const intercourse: any[] = [];

		const arr = item.fbname.split('-');
		// 当前事件数据
		const currentEventData = state.jsplumbData[arr[arr.length - 1] - 1];
		// 源的数据
		const sourceItem = currentEventData.nodeList.find((node) => node.fbname === sourceId);
		const targetItem = currentEventData.nodeList.find((node) => node.fbname === targetId);
		endpoints.forEach((v) => {
			console.log('endpoints', v);
			const i = v.element.id.lastIndexOf('-');
			intercourse.push({
				id: v.element.id.slice(0, i),
				innerText: v.element.innerText,
			});
		});
		item.contact = `${intercourse[0].innerText}(${intercourse[0].id}) => ${intercourse[1].innerText}(${intercourse[1].id})`;
		console.log('7777', intercourse, endpoints);
		if (contextMenuClickId === 0) {
			// this.$message.warning('此功能暂未开发')
			console.log('line click', item);
			ElMessageBox.confirm('此操作将永久删除该连线, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					console.log('确定', currentEventData);
					const EventName = currentEventData.EventName;
					// 将需要删除的连线过滤掉
					const TriggerCond = item.TriggerCond.split(',')
						.filter((item) => {
							if (item.split('.')[0].indexOf(sourceItem.CallFBID) === -1) {
								console.log(item);
								return item;
							}
						})
						.join(',');
					const params = {
						ProgramType: 0,
						FlowID: routeParams.FlowID,
						FBName: EventName,
						CallFBID: item.CallFBID,
						TriggerCond,
					};
					console.log('params:', params);
					httpRequest.Post('/crm/update_dev_flow_program_fbd.action', {}, params).then((res) => {
						if (res.code === '0000' && res.success) {
							// 去出该线条的索引
							const deleLineIndex = currentEventData.lineList.find((line) => line.sourceId === sourceId && line.targetId === targetId);
							// 将该线条数据从数组中删除
							currentEventData.lineList.splice(deleLineIndex, 1);
							// 删除实例中的连线
							jsPlumbInstList[arr[arr.length - 1] - 1].deleteConnection(conn);
							targetItem.TriggerCond = TriggerCond;
							ElMessage({
								type: 'success',
								message: '删除成功',
								duration: BASE_API.MSG_SHOW_TIME,
							});
						} else {
							ElMessage({
								type: 'error',
								message: '删除失败',
								duration: BASE_API.MSG_SHOW_TIME,
							});
						}
					});
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消删除',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				});
		} else if (contextMenuClickId === 1) drawerRef.value.open(item, conn);
	};
	// 右侧内容区-当前项右键菜单点击回调(节点)
	const onCurrentNodeClick = (item) => {
		const { contextMenuClickId } = item;

		if (contextMenuClickId === 0) {
			ElMessageBox.confirm('此操作将永久删除该功能块, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					// this.$message.warning('此功能暂未开发')
					const arr = item.fbname.split('-');
					const index = arr[arr.length - 1] - 1;
					const EventName = state.jsplumbData[index].EventName;
					console.log(EventName);
					// return
					const nodeList = state.jsplumbData[index].nodeList;
					const lineList = state.jsplumbData[index].lineList;
					let currentSourceNodeIndex: number | null = null; // 当前节点的索引 源
					let currentTargetNodeIndex: number | null = null; // 当前节点的索引 目标
					nodeList.forEach((node, index) => {
						if (node.fbname === item.fbname) {
							currentSourceNodeIndex = index;
						}
						console.log('node:', node);
						if (node.TriggerCond) {
							let newTriggerCond = node.TriggerCond;
							const triggerCondArr = node.TriggerCond.split(',');
							triggerCondArr.forEach((t) => {
								const nodeId = t.split('.')[0]; // ${1}
								console.log(nodeId, item.CallFBID, nodeId.indexOf(item.CallFBID));
								if (nodeId.indexOf(item.CallFBID) === 2) {
									newTriggerCond = newTriggerCond.replace(t, '');
								}
							});
							if (newTriggerCond !== node.TriggerCond) {
								console.log('TriggerCond:', node.TriggerCond, ' newTriggerCond:', newTriggerCond);
								currentTargetNodeIndex = index;
								httpRequest
									.Post(
										'/crm/update_dev_flow_program_fbd.action',
										{},
										{
											ProgramType: 0,
											FlowID: routeParams.FlowID,
											FBName: EventName,
											CallFBID: node.CallFBID,
											TriggerCond: newTriggerCond,
										}
									)
									.then((res) => {
										if (res.code !== '0000' && !res.success) {
											ElMessage({
												type: 'error',
												message: '清除和当前功能块关联的线条失败',
												duration: BASE_API.MSG_SHOW_TIME,
											});
										}
									});
							}
						}
					});
					console.log('nodeList', nodeList);
					console.log('node', item);
					// return
					// 删除功能块
					httpRequest
						.Post(
							'/crm/delete_dev_flow_program_fbd.action',
							{},
							{
								ProgramType: 0,
								FlowID: routeParams.FlowID,
								FBName: EventName,
								CallFBID: item.CallFBID,
							}
						)
						.then((res) => {
							if (res.code === '0000' && res.success) {
								ElMessage({
									type: 'success',
									message: '删除功能块成功',
									duration: BASE_API.MSG_SHOW_TIME,
								});
								const index = lineList.find(
									(item) => nodeList[currentSourceNodeIndex!].fbname === item.sourceId && nodeList[currentTargetNodeIndex!].fbname === item.targetId
								);
								nodeList.splice(currentSourceNodeIndex, 1);
								lineList.splice(index, 1);
							} else {
								ElMessage({
									type: 'error',
									message: '删除功能块失败',
									duration: BASE_API.MSG_SHOW_TIME,
								});
							}
						});
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消删除',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				});
		}
	};
	// 设置线的 label
	const setLineLabel = (obj) => {
		const { sourceId, targetId, label, color, FBItem } = obj;
		console.log('setLineLabel conn', obj, state.currentFlowAreaID, jsPlumbInstList[state.currentFlowAreaID!]);
		const conn = jsPlumbInstList[state.currentFlowAreaID!].getConnections({
			source: sourceId,
			target: targetId,
		})[0];

		if (label) {
			conn.setLabel(label);
		}
		conn.setPaintStyle({ stroke: color || '#228CEF' });
		console.log('setLineLabel', conn);
		if (label) {
			conn.addClass('line-box');
		}
		const flowData = state.jsplumbData[state.currentFlowAreaID!];
		flowData.lineList.forEach((v) => {
			if (v.sourceId === sourceId && v.targetId === targetId) v.label = label;
		});
		const sourceNodeItem = flowData.nodeList.find((item) => item.fbname === sourceId);
		const targetNodeItem = flowData.nodeList.find((item) => item.fbname === targetId);
		console.log('FBItem', FBItem);
		// 更改线条触角
		const newTriggerArr = FBItem.TriggerCond.split(',').map((t) => {
			const arr = t.split('.');

			if (arr[0] === '${' + sourceNodeItem.CallFBID + '}' && arr[1] !== '${' + FBItem.antenna + '}') {
				return '${' + sourceNodeItem.CallFBID + '}.${' + FBItem.antenna + '}';
			} else {
				return t;
			}
		});
		//
		const newTrigger = newTriggerArr.join(',');
		let TriggerCond = '';
		if (FBItem.TriggerCond && newTrigger === FBItem.TriggerCond) {
			TriggerCond = FBItem.TriggerCond + ',${' + sourceNodeItem.CallFBID + '}.${' + FBItem.antenna + '}';
		} else if (newTrigger) {
			TriggerCond = newTrigger;
		} else {
			TriggerCond = '${' + sourceNodeItem.CallFBID + '}.${' + FBItem.antenna + '}';
		}
		const params = {
			ProgramType: 0,
			FlowID: routeParams.FlowID,
			FBName: flowData.EventName,
			CallFBID: FBItem.CallFBID,
			TriggerCond,
		};
		console.log('修改fb', params);
		httpRequest.Post('/crm/update_dev_flow_program_fbd.action', {}, params).then((res) => {
			if (res.code === '0000' && res.success) {
				ElMessage({
					type: 'success',
					message: '修改成功',
					duration: BASE_API.MSG_SHOW_TIME,
				});
				targetNodeItem.TriggerCond = TriggerCond;
			} else {
				ElMessage({
					type: 'error',
					message: '修改失败',
					duration: BASE_API.MSG_SHOW_TIME,
				});
			}
		});
	};

	// 查询流程事件
	const handleQueryFlowEvent = () => {
		const data = { FlowID: routeParams.FlowID };
		httpRequest.Post('/crm/query_flow_event.action', {}, data).then((res) => {
			if (res.code !== '0000' && !res.success) {
				ElMessage({
					type: 'error',
					message: '查询流程事件失败',
					duration: BASE_API.MSG_SHOW_TIME,
				});
				return;
			}
			state.flowEventList = res.Records || [];
			console.log('handleQueryFlowEvent', state.flowEventList);
			// 将事件变量保存到关键字中
			state.flowEventList.forEach((item) => {
				if (item.Vars) {
					keyword.e.push(...item.Vars.split(','));
				}
			});
		});
	};

	// 弹窗处理流程事件的弹窗
	const handleAddOrUpdateEvent = (flag: boolean, index?: number) => {
		state.eventhandlerDialog = true;
		state.isAddEventhandler = flag;
		if (!flag) {
			const currentFlowEvent = state.flowEventList[index!];
			console.log('handleAddOrUpdateEvent', currentFlowEvent);

			if (currentFlowEvent.EventType === '2') {
				nextTick(() => {
					console.log('eventHandlerRef', eventHandlerRef.value);
					eventHandlerRef.value!.msgEventData.EventName = currentFlowEvent.EventName;
					eventHandlerRef.value!.msgEventData.MsgID = toHex(currentFlowEvent.TriggerID)!;
					eventHandlerRef.value!.msgEventData.isErrEndFlow = currentFlowEvent.ErrCompleteSession === '1' ? true : false;
				});
			} else if (currentFlowEvent.EventType === '3') {
				nextTick(() => {
					eventHandlerRef.value!.timeoutData.EventName = currentFlowEvent.EventName;
					eventHandlerRef.value!.timeoutData.TimeoutID = currentFlowEvent.TriggerID;
					eventHandlerRef.value!.timeoutData.isErrEndFlow = currentFlowEvent.ErrCompleteSession === '1' ? true : false;
				});
			}
		}
		console.log('handleAddEvent length', jsPlumbInstList.length);
		// this.jsPlumbInst.push(this.createJsPlumbInst(this.jsPlumbInst.length))
		// this.jsplumbData.push({
		//   nodeList: [],
		//   lineList: []
		// })
	};
	// 提交处理事件
	const handleSubmitEvent = async () => {
		if (!eventHandlerRef.value) {
			console.error('组件实例没有获取到:', eventHandlerRef);
			return;
		}
		const { currentTag, msgEventData, timeoutData } = eventHandlerRef.value;
		console.log('eventHandlerRef', currentTag, msgEventData, timeoutData);

		const data: Record<string, any> = {};
		data.FlowID = routeParams.FlowID;
		data.EventName = msgEventData.EventName;
		if (state.isAddEventhandler) {
			data.OrderNum = parseInt(state.flowEventList[state.flowEventList.length].OrderNum) + 1;
		}
		const url = state.isAddEventhandler ? '/crm/add_dev_flow_event.action' : '/crm/update_dev_flow_event.action';
		if (currentTag === '0') {
			data.TriggerID = toHex1(msgEventData.MsgID);
			data.EventType = 2;
			data.ErrCompleteSession = msgEventData.isErrEndFlow ? 1 : 0;
			console.log('消息事件', data);
			const res = await httpRequest.Post(url, {}, data);
			if (res.code !== '0000' && res.success !== true) {
				return ElMessage({
					type: 'error',
					message: `${state.isAddEventhandler ? '添加' : '修改'}流程事件失败`,
					duration: BASE_API.MSG_SHOW_TIME,
				});
			}
			ElMessage({
				type: 'success',
				message: `${state.isAddEventhandler ? '添加' : '修改'}流程事件成功`,
				duration: BASE_API.MSG_SHOW_TIME,
			});
			handleQueryFlowEvent(); // 查询最新数据
		} else if (currentTag === '1') {
			data.TriggerID = timeoutData.TimeoutID;
			data.EventType = 3;
			data.ErrCompleteSession = timeoutData.isErrEndFlow ? 1 : 0;
			console.log('定时器', data);

			const res = await httpRequest.Post(url, {}, data);
			if (res.code !== '0000' && res.success !== true) {
				return ElMessage({
					type: 'error',
					message: `${state.isAddEventhandler ? '添加' : '修改'}流程事件失败`,
					duration: BASE_API.MSG_SHOW_TIME,
				});
			}
			ElMessage({
				type: 'success',
				message: `${state.isAddEventhandler ? '添加' : '修改'}流程事件成功`,
				duration: BASE_API.MSG_SHOW_TIME,
			});
			handleQueryFlowEvent(); // 查询最新数据
		}
		// 添加画布以及参数
		if (state.isAddEventhandler) {
			jsPlumbInstList.push(createJsPlumbInst(jsPlumbInstList.length));
			state.jsplumbData.push({
				varList: [],
				nodeList: [
					{
						class: 'start-node-flow',
						descption: '开始',
						fbname: 'start-fb',
						id: 'start-fb',
						left: '3px',
						top: '70px',
						icon: 'el-icon-open',
					},
				],
				lineList: [],
			});
		}
		state.eventhandlerDialog = false;
	};
	const handleFlowNode = (currentIndex: string) => {
		state.currentIndex = currentIndex;
		console.log(state.currentIndex);
	};
	// 调用功能块 弹窗
	const handleCallFB = (item: Record<string, any>, index: number) => {
		state.EditCallFB = true;
		state.dragFBToEventIndex = index;
		if (/start-fb|end-fb|session-end-fb/.test(item.fbname)) {
			return ElMessage({
				type: 'warning',
				message: '该功能块没有触发事件',
				duration: BASE_API.MSG_SHOW_TIME,
			});
		}
		httpRequest
			.Post('/crm/query_flow_program_fbd.action', {
				CallFBName: item.CallFBName,
				FlowID: routeParams.FlowID,
				FBName: state.jsplumbData[index].EventName,
				CallFBID: item.CallFBID,
			})
			.then((res) => {
				if (res.code === '0000' && res.success) {
					const record = res.Records[0];
					const InputAssign = JSON.parse(record.InputAssign.replace(/\\/g, ''));
					const Position = JSON.parse(record.Position.replace(/\\/g, ''));
					item.left = Position.left;
					item.top = Position.top;
					item.AfterCode = record.AfterCode;
					item.PreCode = record.PreCode;
					item.inputVars = record.InputAssign;
					console.log(record);
					state.funcPieceCalldialog = true;
					const data = { ...item };
					data.inputVars = Object.keys(InputAssign).map((key) => ({ label: key, value: InputAssign[key] }));
					nextTick(() => {
						FBCallRef.value.FBItem = data;
					});
					console.log('功能块参数', data);
				} else {
					ElMessage({
						type: 'error',
						message: '查询功能块信息错误',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				}
			});
	};
	// 查询事件里的功能块
	const handleQueryFlowEventFBD = async (params: Record<string, any>, nodeTypeList: Record<string, any>[]) => {
		const res = await httpRequest.Post('/crm/query_flow_program_fbd.action', {}, params);
		if (res.code !== '0000' && !res.success) {
			ElMessage({
				type: 'success',
				message: '查询流程程序图表失败',
				duration: BASE_API.MSG_SHOW_TIME,
			});
			return;
		}

		const records = res.Records || [];
		console.log('records:', records);
		console.log('flowList:', state.flowEventList);
		state.flowEventList.forEach((event, index) => {
			const startNode = {
				class: 'start-node-flow',
				descption: '开始',
				fbname: 'start-fb-' + index + 1,
				id: 'start-fb-' + index + 1,
				left: '3px',
				top: '70px',
				icon: 'el-icon-open',
				CallFBID: 0,
			};
			// 先插入event初始数据
			const length = state.jsplumbData.push({
				EventName: event.EventName,
				nodeList: [startNode],
				lineList: [],
			});
			if (records.length > 0) {
				// 节点
				records.forEach((item) => {
					console.log('records itme:', item);
					const positoin = JSON.parse(item.Position.replace(/\\/g, ''));
					const FBItem = nodeTypeList.find((fb) => fb.FBName === item.CallFBName);
					const inputAssign = JSON.parse(item.InputAssign.replace(/\\/g, ''));

					console.log('FBItem', FBItem, { ...nodeTypeList });
					const node = {
						class: 'small-rectangle-flow',
						descption: FBItem?.FBName,
						fbname: item.CallFBName + '-' + length,
						id: item.CallFBName + '-' + length,
						left: positoin.left,
						top: positoin.top,
						inputVars: inputAssign,
						PreCode: item.PreCode,
						AfterCode: item.AfterCode,
						TriggerCond: item.TriggerCond,
						CallFBID: item.CallFBID,
					};
					if (event.EventName === item.FBName) {
						if (state.jsplumbData[length - 1].nodeList.length === 1) {
							state.jsplumbData[length - 1].nodeList.push(node);
							state.jsplumbData[length - 1].lineList = [{ sourceId: startNode.fbname, targetId: item.CallFBName + '-' + length, label: '' }];
							console.log('开始', state.jsplumbData[length - 1]);
						} else {
							state.jsplumbData[length - 1].nodeList.push(node);
						}
					}
				});
				// 线
				records.forEach((item) => {
					if (event.EventName === item.FBName) {
						// 查找当前线是在那个画布
						if (item.TriggerCond) {
							console.log('线 item:', item);
							const lines = item.TriggerCond.split(',').map((item2) => {
								const arr = item2.split('.');
								console.log(arr);
								const FBID = arr[0].slice(2, arr[0].length - 1);
								const antenna = arr[1].slice(2, arr[1].length - 1);

								const nodeItem = state.jsplumbData[length - 1].nodeList.find((node) => node.CallFBID === FBID);
								// const sourceId = this.jsplumbData[length - 1].nodeList[FBID].fbname
								console.log('item2', nodeItem);
								if (nodeItem) {
									return { sourceId: nodeItem.fbname, targetId: item.CallFBName + '-' + length, antenna, isPop: false };
								}
							});
							state.jsplumbData[length - 1].lineList.push(...lines);
						}
					}
				});
			}
		});
	};
	// 弹窗 Init or timeout 代码编辑框
	const handleSCodeEditor = (type: 'Timeout' | 'Init') => {
		console.log('handleSCodeEditor:', type);
		state.EventType = type;
		state.isCodeEditorDialog = true;

		// 查询cs 代码
		const params = { ProgramType: 1, FlowID: routeParams.FlowID, FBName: type };
		httpRequest.Post('/crm/query_flow_program_cs.action', {}, params).then((res) => {
			if (res.code !== '0000' && !res.success) {
				ElMessage({
					type: 'error',
					message: `查询${type}数据失败`,
					duration: BASE_API.MSG_SHOW_TIME,
				});
				return;
			}
			const records = res.Records || [];
			if (records.length > 0) {
				state.CSCode = records[0].Contents;
				console.log(state.CSCode);
				state.addCodeOrEditCode = 'edit';
			} else {
				state.addCodeOrEditCode = 'add';
			}
		});
	};
	// 关闭CSCodeEditor
	const handleCSCodeClose = () => {
		ElMessageBox.confirm('确定要关闭编辑器吗', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(() => {
				state.CSCode = '';
				state.isCodeEditorDialog = false;
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: `已取消`,
					duration: BASE_API.MSG_SHOW_TIME,
				});
			});
	};
	// 提交 CS code
	const handleSubmitCSCode = () => {
		const data = { ProgramType: 1, FlowID: routeParams.FlowID, FBName: state.EventType, Contents: state.CSCode };
		console.log('handleSubmitCSCode: data', data);
		// this.isCodeEditorDialog = false
		// return
		const urls = {
			add: '/crm/add_dev_flow_program_cs.action',
			edit: '/crm/update_dev_flow_program_cs.action',
		};
		httpRequest.Post(urls[state.addCodeOrEditCode], {}, data).then((res) => {
			if (res.code === '0000' && res.success) {
				ElMessage({
					type: 'success',
					message: `${state.addCodeOrEditCode === 'add' ? '添加' : '修改'}${state.EventType}事件成功`,
					duration: BASE_API.MSG_SHOW_TIME,
				});

				state.isCodeEditorDialog = false;
			} else {
				ElMessage({
					type: 'error',
					message: `${state.addCodeOrEditCode === 'add' ? '添加' : '修改'}${state.EventType}事件失败`,
					duration: BASE_API.MSG_SHOW_TIME,
				});
				state.isCodeEditorDialog = false;
			}
		});
	};

	// 功能块移入
	const handleNodeMouseover = (e: Event, node: Record<string, any>) => {
		state.timer = setTimeout(() => {
			console.log('hehei', node);
			state.isFBDateildialog = true;
			state.FBDateilData = node;
		}, 3000);
		// console.log('移入', e)
	};
	// 功能块移除
	const handleNodeMouseout = (e: Event) => {
		// this.isFBDateildialog = false
		// console.log('移除', e)
		clearTimeout(state.timer);
	};
	// 处理调用功能块
	const handleFuncPieceCall = () => {
		const FBitem = FBCallRef.value.FBItem;
		console.log('FBItem', FBitem);
		// return
		console.log('dragFBToEventIndex', state.dragFBToEventIndex);
		const EventName = state.flowEventList[state.dragFBToEventIndex!].EventName;
		const data: Record<string, any> = { ProgramType: 0, FlowID: routeParams.FlowID, FBName: EventName }; //  TriggerCond: FBitem.TriggerCond
		const inputVars = FBitem.inputVars.reduce((pre, item, index) => {
			pre[item.label] = item.value;
			return pre;
		}, {});
		const nodeList = state.jsplumbData[state.dragFBToEventIndex!].nodeList;
		const i = FBitem.fbname.lastIndexOf('-');
		const CallFBName = FBitem.fbname.slice(0, i);
		data.PreCode = FBitem.PreCode;
		data.AfterCode = FBitem.AfterCode;
		data.InputAssign = JSON.stringify(inputVars);
		data.Position = JSON.stringify({ left: FBitem.left, top: FBitem.top });
		data.CallFBID = nodeList[nodeList.length - 1].CallFBID;
		data.CallFBName = CallFBName;

		// console.log('handleFuncPieceCall', data, FBitem)
		// return
		if (state.EditCallFB) {
			httpRequest.Post('/crm/update_dev_flow_program_fbd.action', {}, data).then((res) => {
				if (res.code === '0000' && res.success) {
					ElMessage({
						type: 'success',
						message: '修改成功',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				} else {
					ElMessage({
						type: 'error',
						message: '修改失败',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				}
			});
		} else {
			httpRequest.Post('/crm/add_dev_flow_program_fbd.action', {}, data).then((res) => {
				if (res.code === '0000' && res.success) {
					ElMessage({
						type: 'success',
						message: '添加成功',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				} else {
					ElMessage({
						type: 'error',
						message: '添加失败',
						duration: BASE_API.MSG_SHOW_TIME,
					});
				}
			});
		}
		state.funcPieceCalldialog = false;

		console.log('handleFuncPieceCall', data);
	};
	// 提交事件变量
	const handleEventVarSubmit = () => {
		const data = { ...state.flowEventList[state.currentEventVarIndex!] };
		console.log('handleEventVarSubmit data:', data);
		httpRequest.Post('/crm/update_dev_flow_event.action', {}, data).then((res) => {
			if (res.code === '0000' && res.success) {
				ElMessage({
					type: 'success',
					message: `${state.isEditEventVar ? '修改' : '添加'}成功`,
					duration: BASE_API.MSG_SHOW_TIME,
				});
			} else {
				ElMessage({
					type: 'error',
					message: `${state.isEditEventVar ? '修改' : '添加'}失败`,
					duration: BASE_API.MSG_SHOW_TIME,
				});
			}
		});
		state.addEventVarDialog = false;
	};
	const deleteConnectionLine = (jsPlumbInstIndex: number) => {
		const lineItem = state.jsplumbData[jsPlumbInstIndex].lineList[state.currentPushLineListIndex!];
		const connection = jsPlumbInstList[jsPlumbInstIndex].getConnections({
			source: lineItem.sourceId,
			target: lineItem.targetId,
		});
		state.jsplumbData[jsPlumbInstIndex].lineList.splice(state.currentPushLineListIndex, 1);
		jsPlumbInstList[jsPlumbInstIndex].deleteConnection(connection[0]);
	};
	return {
		...toRefs(state),
		eventHandlerRef,
		FBCallRef,
		drawerRef,
		contextmenuLineRef,
		contextmenuNodeRef,
		createJsPlumbInst,
		initJsPlumbConnection,
		handleNodeContextMenu,
		onCurrentLineClick,
		onCurrentNodeClick,
		setLineLabel,
		handleFlowNode,
		handleQueryFlowEvent,
		handleAddOrUpdateEvent,
		handleCallFB,
		handleQueryFlowEventFBD,
		handleSCodeEditor,
		handleCSCodeClose,
		handleSubmitCSCode,
		handleSubmitEvent,
		handleNodeMouseover,
		handleNodeMouseout,
		handleFuncPieceCall,
		handleEventVarSubmit,
		deleteConnectionLine,
	};
}
